import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleEnum } from 'src/role/role.enum';
import { UserGuard } from 'src/role/role.guard';
import { SystemService } from './system.service';
import { System } from './system.entity';
import { Forbidden, Http } from 'src/util/http';
import { AuthGuard } from '@nestjs/passport';
import { DeptService } from 'src/dept/dept.service';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { UserService } from 'src/user/user.service';
import { FindOptionsWhere, In, Not } from 'typeorm';
import { Dept } from 'src/dept/dept.entity';

@Controller('api/system')
@UseGuards(AuthGuard('jwt'))
@ApiTags('职场管理')
export class SystemController {
  constructor(
    private readonly systemService: SystemService,
    private readonly deptService: DeptService,
    private readonly userService: UserService,
  ) {}

  @Get(':id/system/set')
  @ApiOperation({ summary: 'boos切换职场' })
  @UseGuards(UserGuard([RoleEnum.boos]))
  public async systemSet(
    @Param('id') id: number,
    @CurrentUser() user: UserSys,
  ) {
    const system = await this.systemService.system.findOne({ where: { id } });
    user.system = system;
    // console.log("id", id, system.id)
    await this.userService.userSys.save(user);
  }

  @Get('getall')
  @ApiOperation({ summary: '获取所有职场' })
  async getall(@CurrentUser() user: UserSys) {
    let arr: System[] = [];
    if (user.role === RoleEnum.boos)
      arr = await this.systemService.system.find();
    else arr = [user.system];
    for (let i = 0; i < arr.length; i++) {
      arr[i].responsibilitys = await this.userService.findsBy({
        role: RoleEnum.director,
        system: {
          id: arr[i].id,
        },
      });
    }
    return arr;
  }

  @Get('getAndDept')
  @ApiOperation({ summary: '获取职场及部门' })
  async getAndDept(@CurrentUser() user: UserSys) {
    const system =
      user.role === RoleEnum.boos
        ? await this.systemService.system.find()
        : [user.system];
    const arr = new Array(system.length).fill(0);
    for (let i = 0; i < arr.length; i++) {
      const where: FindOptionsWhere<Dept> = { system: { id: system[i].id } };
      if (user.role === RoleEnum.manager) where.id = user.dept.id;
      arr[i] = {
        system: system[i],
        depts: (await this.deptService.find(where)).map((e) => ({
          ...e,
          parent: undefined,
        })),
      };
    }
    return arr;
  }

  @Post('add')
  @ApiOperation({ summary: '添加职场' })
  async add(@Body() data: System, @CurrentUser() user: UserSys) {
    if (user.role !== RoleEnum.boos) throw Forbidden;
    return await this.systemService.create(data);
  }

  @Post(':id/upd')
  @ApiOperation({ summary: '修改职场' })
  async upd(
    @Param('id') id: number,
    @Body() { name, responsibility, comment },
    @CurrentUser() user: UserSys,
  ) {
    if (user.role !== RoleEnum.boos) throw Forbidden;
    const system = await this.systemService.system.findOne({
      where: { id },
      relations: [],
    });
    system.name = name;
    system.comment = comment;
    await this.userService.userSys.update(
      {
        role: RoleEnum.director,
      },
      {
        role: RoleEnum.member,
      },
    );
    await this.userService.userSys.update(
      {
        id: In(responsibility),
        role: Not(RoleEnum.boos),
      },
      {
        system,
        dept: null,
        role: RoleEnum.director,
      },
    );
    return this.systemService.system.save(system);
  }

  @Post('administrators')
  @ApiOperation({ summary: '将员工设置为职场管理员' })
  @UseGuards(UserGuard([RoleEnum.boos]))
  async administrators(@Body() body: number[]) {
    return await this.systemService.setAdmin(body);
  }

  @Get(':id/del')
  @ApiOperation({ summary: '删除职场（测试' })
  @UseGuards(UserGuard([RoleEnum.boos]))
  async del(@Param('id') id: number) {
    try {
      await this.deptService.dept.delete({
        system: {
          id,
        },
      });
      await this.systemService.system.delete(id);
    } catch (e) {
      console.log(e);
      throw Http.forbidden(
        '删除失败，只能删除毫无数据的职场。若要删除职场，请将所有数据删除后再进行操作！',
      );
    }
  }
}
